package com.aids_malaria.ui.datacollect;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.adapter.PersonSelectAdapter;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.base.BaseQuickAdapter;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AreaC;
import com.aids_malaria.http.response.PersonData;
import com.aids_malaria.util.GsonUtil;
import com.aids_malaria.util.LogUtil;
import com.aids_malaria.util.ResourceUtil;
import com.aids_malaria.util.StringUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.titlebar.TitleBar;
import com.luck.picture.lib.rxbus2.Subscribe;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 人员选择
 */
public class PersonSelectActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    TitleBar title_bar;
    @BindView(R.id.et_county)
    TextView et_county;
    @BindView(R.id.et_village)
    TextView et_village;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.et_id_num)
    EditText et_id_num;
    @BindView(R.id.et_id)
    EditText et_id;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private List<PersonData> mData = new ArrayList<>();
    private PersonSelectAdapter personSelectAdapter;

    private String county_code = "",county_name = "";
    private String village_code = "",village_name;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_select;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitleBar(title_bar, ResourceUtil.getString(R.string.person_select));
        initRefreshLayout();
    }

    @Override
    protected void initData() {
        super.initData();
        initRecycleView();
        // 根据要求，默认先不要加载全部数据
        if (!isOnLine()){
            getPerson();
        }
    }

    private void initRecycleView() {
        rv_data.setLayoutManager(new LinearLayoutManager(mContext));
        personSelectAdapter = new PersonSelectAdapter(mContext,R.layout.item_person_select,mData);
        rv_data.setAdapter(personSelectAdapter);
        personSelectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent();
                intent.putExtra("personData",mData.get(position));
                setResult(3,intent);
                finish();
            }
        });
    }

    private void initRefreshLayout() {
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getPerson();
            }
        });
    }

    @OnClick({R.id.ll_back, R.id.iv_search,R.id.iv_county_select,R.id.iv_village_select,R.id.et_county,R.id.et_village})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_search:
                getPerson();
                break;
            case R.id.iv_county_select:
            case R.id.et_county:
                Bundle b = new Bundle();
                b.putInt(Events.TYPE_KEY,Events.TYPE_PERSON_SELECT);
                startActivity(CountySelectActivity.class,b);
                break;
            case R.id.iv_village_select:
            case R.id.et_village:
                // 选择村
                Bundle bundle = new Bundle();
                bundle.putInt(Events.TYPE_KEY,Events.TYPE_PERSON_SELECT);
                bundle.putString("county_code",county_code);
                bundle.putString("county_name",county_name);
                startActivity(VillageSelectActivity.class,bundle);
                break;
        }
    }

    /**
     * 村选择回调
     * @param villageSelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.VillageSelectEvent villageSelectEvent) {
        if (villageSelectEvent.getType() == Events.TYPE_PERSON_SELECT){
            village_code = villageSelectEvent.getAreaV().getVillage_code();
            village_name = villageSelectEvent.getAreaV().getVillage_name();
            et_village.setText(villageSelectEvent.getAreaV().getVillage_name());
        }
    }

    /**
     * 县选择回调
     *
     * @param countySelectEvent
     */
    @Subscribe
    public void onCodeEvent(Events.CountySelectEvent countySelectEvent) {
        if (countySelectEvent.getType() == Events.TYPE_PERSON_SELECT){
            AreaC areaC = countySelectEvent.getAreaC();
            county_code = areaC.getCounty_code();
            county_name = areaC.getCounty_name();
            et_county.setText(county_name);
            et_village.setText("");
            village_code = "";
            village_name = "";
        }
    }

    private void getPerson(){
        if(isOnLine()){
            HashMap<String, Object> map = new HashMap<>();
            map.put("identity_code",et_id_num.getText().toString().trim());
            map.put("name",et_name.getText().toString().trim());
            map.put("original_id",et_id.getText().toString().trim());
            map.put("residential_adress_code","");
            if (!TextUtils.isEmpty(county_code)){
                map.put("residential_adress_code",county_code);
            }
            if (!TextUtils.isEmpty(village_code)){
                map.put("residential_adress_code",village_code);
            }
            map.put("is_photo","0");
            RetrofitFactory.getInstance().createApi(RetrofitApi.class).getPerson(map)
                    .compose(RxScheduler.rxSchedulerTransform())
                    .subscribe(new BaseObserver<List<PersonData>>() {

                        @Override
                        protected void onStart() {
                            getLoadingDialog().show();
                        }

                        @Override
                        protected void onSuccess(List<PersonData> data) throws Exception {
                            if (data != null){
                                mData.clear();
                                mData.addAll(data);
                            }
                            if (mData.size() == 0 ){
                                ToastUtil.showToast(R.string.nodata);
                            }
                            personSelectAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFinish() {
                            getLoadingDialog().dismiss();
                            refresh_layout.finishRefresh();
                        }
                    });
        }else{
//            List<PersonData> personDataList = LiteOrmUtil.queryAll(PersonData.class);
            List<PersonData> personDataList = DBManager.get().personDataDao().getAll();
            Log.d("人员列表数量" ,personDataList.size() + "");
            for (PersonData personData : personDataList) {
                personData.setPhoto("");//去掉图片base64数据
            }
            LogUtil.d("personDataList:--------"+ GsonUtil.beanToJson(personDataList));
            mData.clear();
            if (personDataList != null && personDataList.size() > 0){
                for (PersonData personData : personDataList) {
                    String identity_code = et_id_num.getText().toString().trim();
                    String name = et_name.getText().toString().trim();
                    String original_id = et_id.getText().toString().trim();
                    if(!StringUtil.isEmpty(county_name) && !personData.getResidential_county_name().equals(county_name)){
                        //现居住地县筛选
                        continue;
                    }
                    if(!StringUtil.isEmpty(village_name) && !personData.getResidential_village_name().equals(village_name)){
                        //现居住地县筛选
                        continue;
                    }
                    if (!StringUtil.isEmpty(identity_code) && !personData.getIdentity_code().contains(identity_code)){
                        continue;
                    }
                    if (!StringUtil.isEmpty(name) && !personData.getName().contains(name)){
                        continue;
                    }
                    if (!StringUtil.isEmpty(original_id) && !personData.getOriginal_id().contains(original_id)){
                        continue;
                    }
                    personData.setPhoto("");
                    mData.add(personData);
                }

            }
            if (mData.size() == 0 ){
                ToastUtil.showToast(R.string.nodata);
            }
            personSelectAdapter.notifyDataSetChanged();
        }

    }

}
